//
//  ISqlite.m
//  SqliteTrial
//
//  Created by Aries on 11-7-28.
//  Copyright 2011年 windvoice. All rights reserved.
//

#import "ISqlite.h"


@implementation ISqlite

@synthesize database,filename;

- (id)init
{
    NSAssert(0,@"Never Use this.Please Call Use initWithDatabaseFileName:(NSString*)");
    return nil;
}

- (id) initWithDatabaseFileName:(NSString*) dbfileName
{
    self =[super init];
    
    if(self!=nil)
    {
        if([self open:dbfileName] == 1)
            [self close];
    }
    
    return self;
}

- (int) open:(NSString*) dbfilename
{
    self.filename = dbfilename;
    NSString *documentsDirectory=[[NSBundle mainBundle] resourcePath];
    
    if(sqlite3_open([[documentsDirectory stringByAppendingPathComponent:dbfilename] UTF8String],&database) != SQLITE_OK)
    {
        NSLog(@"Failed to create sqlite database!");
        return 0;
    }
    return 1;    
}

- (int) close
{
    sqlite3_close(self.database);
    return 1;
}

- (int) executeNonQuery:(NSString*) sqlCommand
{
    if (![self open:self.filename]) 
    {
        return NO;
    }
    
    char* errorMsg = NULL;
    if(sqlite3_exec(self.database, [sqlCommand UTF8String],0, NULL, &errorMsg) == SQLITE_OK)
    {
        [self close];
        return YES;
    }
    else 
    {
        printf("execute command failed, command:'%s'",errorMsg);
        [self close];
        return NO;
    }    
    
    return YES;
}

- (NSArray*) executeTable:(NSString*) sqlCommand
{
    if (![self open:self.filename]) 
    {
        return nil;
    }
    
    int row = 0;
    int column = 0;
    char* errorMsg = NULL;
    char** dbResult = NULL;
    
    NSMutableArray* array = [[NSMutableArray alloc] init];
    [array autorelease];
    
    if(sqlite3_get_table(self.database, [sqlCommand UTF8String], &dbResult, &row,&column,&errorMsg ) == SQLITE_OK)
    {
        if (0 == row) 
        {
            [self close];
            return nil;
        }
        
        int index = column;
        for(int i = 0; i < row ; i++ ) 
        {  
            NSMutableDictionary* row = [[NSMutableDictionary alloc] init];
            for(int j = 0 ; j < column; j++ ) 
            {
                if (dbResult[index]) 
                {
                    NSString* value = [[NSString alloc] initWithUTF8String:dbResult[index]];
                    NSString* key = [[NSString alloc] initWithUTF8String:dbResult[j]];
                    [row setObject:value forKey:key];
                    [value release];
                    [key release];                    
                }
                
                index ++;
            } 
            [array addObject:row];
            [row release];            
        }
    }
    else 
    {
        printf("%s",errorMsg);
        [self close];
        return nil;
    }
    
    [self close];
    
    return array;
}


- (void)dealloc
{
    self.database = nil;
    self.filename = nil;
    [super dealloc];
}

@end
